import 'package:flutter/material.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String debugLabel = 'Unknown';
  final JPush jPush = new JPush();

  Future<void> initJPushPlatformState() async {
    String platformVersion;
    try {
      jPush.addEventHandler(
        // 接收通知回调方法。
        onReceiveNotification: (Map<String, dynamic> message) async {
          print("flutter onReceiveNotification: $message");
          //接收推送的信息
          setState(() {
            debugLabel = '接收到推送：$message';
          });
        },
        // 点击通知回调方法。
        onOpenNotification: (Map<String, dynamic> message) async {
          print("flutter onOpenNotification: $message");
        },
        // 接收自定义消息回调方法。
        onReceiveMessage: (Map<String, dynamic> message) async {
          print("flutter onReceiveMessage: $message");
        },
      );
    } catch (PlatformException) {
      platformVersion = '平台版本获取失败，请检查配置';
    }

    jPush.setup(
      appKey: "01c42f57eae5403abebbd8f9",
      channel: "theChannel",
      production: false,
      debug: false, // 设置是否打印 debug 日志
    );

    //无错误返回
    if (!mounted) return;
    //有错误则将标签设置为错误信息
    setState(() {
      debugLabel = platformVersion;
    });
  }

  @override
  void initState() {
    super.initState();
    //初始化极光推送平台
    initJPushPlatformState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('极光推送Demo'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Text('推送结果$debugLabel'),
              RaisedButton(
                onPressed: () {
                  //点击3秒后发送的时间戳，这里使用DateTime获取当前时间戳，+3000毫秒也就是3秒后的时间戳
                  var fireDate = DateTime.fromMillisecondsSinceEpoch(
                      DateTime.now().millisecondsSinceEpoch + 3000);
                  //本地的一个推送
                  var localNotification = LocalNotification(
                    id: 234,
                    title: '推送标题',
                    content: '推送的具体内容，看到说明已经推送成功',
                    buildId: 1,
                    fireTime: fireDate,
                    subtitle: '一个副标题',
                  );
                  //使用极光推送本地推送
                  jPush.sendLocalNotification(localNotification).then((res) {
                    setState(() {
                      debugLabel = res;
                    });
                  });
                },
                child: Text('点击发送本地推送'),
              )
            ],
          ),
        ),
      ),
    );
  }
}
